#include "stm32f10x.h"                  // Device header
#include <string.h>
#include <stdio.h>
#include "Delay.h"
#include "OLED.h"
#include "DHT11.h"
#include "Buzzer.h"
#include "usart.h"
#include "esp8266.h"
#include "Motor.h"
#include "Water_pump.h"
#include "ADC_Light_Soil.h"

#define SUBTopic "Up-Leewux"  //设备发送消息的地址
#define PUBTopic "Leewux"//设备接收消息的地址
uint8_t Fan_status,Water_status;
uint16_t Soil_Humi,Lux;
DHT11_Data_TypeDef DHT11_Data;
void Oled_show();
int main(void)
	
{	
	unsigned short timeCount = 0;	//发送间隔变量
	unsigned char *dataPtr = NULL;
	char msg[255];
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	
	Usart1_Init(115200);							//串口1，打印信息用
	Usart2_Init(115200);							//串口2，驱动ESP8266用
	DHT11_Init(); //温度传感器初始化
	UsartPrintf(USART_DEBUG, " Hardware init OK\r\n");
	Water_pump_Init();//初始化水泵
	OLED_Init();//初始化OLED屏幕
	ESP8266_Init();					//初始化ESP8266
	MQTT_SUb(SUBTopic);			//接入MQTT
	My_ADC_Init(); //初始化土壤湿度和光照传感器
	
	
	//Buzzer_init();
	while(1)
	{	
		Fan_status = Motor_Status();//获取风扇开关状态
		Water_status = Water_pump_Status();//获取水泵开关状态
		Soil_Humi = GetSoilHumi();  //获取土壤湿度数据
		Lux = GetLux(); //获取光照流明数据
		Read_DHT11(&DHT11_Data);//轮询温度
		memset(msg, 0x00, 255);//清空缓存
		Oled_show();
		sprintf(msg,"{\\\"Temp\\\": %d\\,\\\"Soil_humi\\\": %d\\,\\\"Light\\\": %d\\,\\\"Led\\\": %d\\,\\\"Fan\\\": %d\\,\\\"Water_pump\\\": %d}"
		,DHT11_Data.temp_int,Soil_Humi,Lux,0,Fan_status,Water_status);
		if(++timeCount >= 50)									//发送间隔2s
		{
			MQTT_PUB(PUBTopic,msg);
			timeCount = 0;
			ESP8266_Clear();
		}
		
		dataPtr = ESP8266_GetHead(3);
		
		if(dataPtr != NULL && (strstr((char*)dataPtr,"{")!= NULL))
		{
			UsartPrintf(USART_DEBUG,"GET data\r\n");
			UsartPrintf(USART_DEBUG,(char*)dataPtr);
			MQTT_RevPro((char*)dataPtr);
		}
		
		Delay_ms(10);
		
	}
}

void Oled_show()
{
	OLED_ShowString(1,1,"Temp:");
	OLED_ShowNum(1,6,DHT11_Data.temp_int,3);//显示温度
	OLED_ShowString(2,1,"Humi:");
	OLED_ShowNum(2,6,Soil_Humi,3);//显示土壤湿度Soil_Humi
	OLED_ShowString(3,1,"Lux:");
	OLED_ShowNum(3,6,Lux,3);//光照流明
}

